package com.iamalive;


import java.util.ArrayList;
import java.util.Iterator;

import com.iamalive.LocalCache.InfoDetails;
import com.iamalive.LocalCache.MediaType;
import com.iamalive.LocalCache.RecipientDetails;

import android.os.Bundle;
import android.app.Dialog;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;

public class AddInfoActivity extends FragmentActivity {

	private EditText mEditTextInfoBody;
	private EditText mEditTextTtl;
	private Button mButtonAddRecipient;
	private Button mButtonSave;
	private Button mButtonCancel;
	private InfoDetails mInfoDetails;
	private ArrayList<RecipientDetails> mNewRecipientsToBeAdded;
	private Context mContext;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_info);
		
		mEditTextInfoBody = (EditText) findViewById(R.id.editTextAddInfoInfoText);
		mButtonAddRecipient = (Button) findViewById(R.id.buttonAddInfoAddRecipient);
		mEditTextTtl = (EditText) findViewById(R.id.editTextAddInfoTtl);
		
		mButtonSave = (Button) findViewById(R.id.buttonAddInfoSave);
		mButtonCancel = (Button) findViewById(R.id.buttonAddInfoCancel);
		mInfoDetails = LocalCache.getSingleInstance().new InfoDetails();
		mNewRecipientsToBeAdded = new ArrayList<LocalCache.RecipientDetails>();
		mContext = getApplicationContext();
		
		mButtonAddRecipient.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onAddRecipientButtonClicked();
            }
        });
				
		mButtonSave.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onSaveButtonClicked();
            }
        });
		
		mButtonCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });		
	}

	
	private void onAddRecipientButtonClicked() {
        // Create custom dialog object
        final Dialog dialog = new Dialog(AddInfoActivity.this);
        // Include dialog.xml file
        dialog.setContentView(R.layout.dialog_add_recipient);
        // Set dialog title
        dialog.setTitle("Add Recipient");

        dialog.show();
        
        RadioButton radioButtonAddExistingRecipient;
        RadioButton radioButtonAddNewRecipient;
        Button buttonOk;
        Button buttonCancel;
        final Spinner nameSpinner;
        final EditText editTextRecipientName;
        final EditText editTextRecipientEmail;
        final EditText editTextRecipientPhone;
        final EditText editTextRecipientAddress;
        final EditText editTextRecipientRelation;

        
        radioButtonAddExistingRecipient = (RadioButton) dialog.findViewById(R.id.radioAddRecipientExisting);
        radioButtonAddNewRecipient = (RadioButton) dialog.findViewById(R.id.radioAddRecipientNew);
        nameSpinner = (Spinner) dialog.findViewById(R.id.spinnerAddRecipientName);
        buttonOk = (Button) dialog.findViewById(R.id.buttonAddRecipientOk);
        buttonCancel = (Button) dialog.findViewById(R.id.buttonAddRecipientCancel);
        editTextRecipientName = (EditText) dialog.findViewById(R.id.editTextAddRecipientName);
        editTextRecipientEmail = (EditText) dialog.findViewById(R.id.editTextAddRecipientEmail);
        editTextRecipientPhone = (EditText) dialog.findViewById(R.id.editTextAddRecipientPhone);
        editTextRecipientAddress = (EditText) dialog.findViewById(R.id.editTextAddRecipientAddress);
        editTextRecipientRelation = (EditText) dialog.findViewById(R.id.editTextAddRecipientRelationship);
        
        //TODO: populate the existing recipient names spinner
        
        
        radioButtonAddExistingRecipient.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				onAddExistingRecipientRadioButtonClicked(v, dialog);
			}
			
			private void onAddExistingRecipientRadioButtonClicked(View v, Dialog d) {				
				Spinner nameSpinner = (Spinner) d.findViewById(R.id.spinnerAddRecipientName);
				
				//if(nameSpinner.isEnabled() == false) {
					(d.findViewById(R.id.textViewAddRecipientExistingName)).setEnabled(true);
					populateNameSpinner(nameSpinner);
					nameSpinner.setEnabled(true);
					enableAddNewRecipientRelatedWidgets(d, false);
				//}
			}
			
			private void populateNameSpinner(Spinner s) {
		        ArrayList<String> listOfRecipientNames = new ArrayList<String>();
		        listOfRecipientNames.add(0, getString(R.string.select_item_to_delete));
		        listOfRecipientNames.addAll(LocalCache.getSingleInstance().getRecipientNameList());
		        Utils.removeExistingStringEntries(listOfRecipientNames, mInfoDetails.listOfRecipients);

				ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, listOfRecipientNames);
				dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				s.setAdapter(dataAdapter);
			}
		});
        
        radioButtonAddNewRecipient.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onAddNewRecipientRadioButtonClicked(v, dialog);
			}
			
			private void onAddNewRecipientRadioButtonClicked(View v, Dialog d) {
				Spinner nameSpinner = (Spinner) d.findViewById(R.id.spinnerAddRecipientName);
				
				//if(nameSpinner.isEnabled() == true) {
					(d.findViewById(R.id.textViewAddRecipientExistingName)).setEnabled(false);
					nameSpinner.setEnabled(false);
					enableAddNewRecipientRelatedWidgets(d, true);
				//}
			}			
			
		});
        
        buttonOk.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Add this recipient to the list of recipients for this info
				
				if(nameSpinner.isEnabled()) {
					String name = nameSpinner.getSelectedItem().toString();

					if(!name.equals(getString(R.string.select_item_to_delete))) {
						mInfoDetails.listOfRecipients.add(name);
						String message = "Recipient " + name + " added for this info.";
						Utils.showToast(mContext, message);
					} else {
						Utils.showToast(mContext, "Select a recipient from the list");
						return;
					}
				} else {
					RecipientDetails newRecipient = LocalCache.getSingleInstance().new RecipientDetails();
					newRecipient.name = editTextRecipientName.getText().toString().trim();
					if(newRecipient.name.length() <= 0) {
						Utils.showToast(mContext, "Recipient name can't be empty");
						return;
					}
					newRecipient.email = editTextRecipientEmail.getText().toString();
					newRecipient.phone = editTextRecipientPhone.getText().toString();
					newRecipient.address = editTextRecipientAddress.getText().toString();
					newRecipient.relationship = editTextRecipientRelation.getText().toString();
					mNewRecipientsToBeAdded.add(newRecipient);
					Utils.showToast(mContext, "New recipient " + newRecipient.name + " added.");
				}
				dialog.dismiss();
			}
		});
        
        buttonCancel.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
	}
	
	private void enableAddNewRecipientRelatedWidgets(Dialog d, boolean trueValue) {
		(d.findViewById(R.id.textViewAddRecipientName)).setEnabled(trueValue);
		(d.findViewById(R.id.editTextAddRecipientName)).setEnabled(trueValue);
		(d.findViewById(R.id.textViewAddRecipientEmail)).setEnabled(trueValue);
		(d.findViewById(R.id.editTextAddRecipientEmail)).setEnabled(trueValue);
		(d.findViewById(R.id.textViewAddRecipientPhone)).setEnabled(trueValue);
		(d.findViewById(R.id.editTextAddRecipientPhone)).setEnabled(trueValue);
		(d.findViewById(R.id.textViewAddRecipientAddress)).setEnabled(trueValue);
		(d.findViewById(R.id.editTextAddRecipientAddress)).setEnabled(trueValue);
		(d.findViewById(R.id.textViewAddRecipientRelationship)).setEnabled(trueValue);
		(d.findViewById(R.id.editTextAddRecipientRelationship)).setEnabled(trueValue);		
	}
	
	
	private void onSaveButtonClicked() {

		mInfoDetails.infoBody = mEditTextInfoBody.getText().toString();
		mInfoDetails.media = MediaType.TEXT;
		String ttl = mEditTextTtl.getText().toString();
		mInfoDetails.ttl = Integer.parseInt(ttl);

		//TODO: validate input and call web-service
		
		LocalCache localCache = LocalCache.getSingleInstance();
		Iterator<RecipientDetails> it = mNewRecipientsToBeAdded.iterator();
		while (it.hasNext()) {
			RecipientDetails recipient = it.next();
			mInfoDetails.listOfRecipients.add(recipient.name);
			localCache.mRecipientDetailsMap.put(recipient.name, recipient);
		}
		
		localCache.mInfoList.add(mInfoDetails);
		
		Utils.showToast(mContext, "New Info added");
		
		finish();		
	}

}
